<?php
class Database {
    private $pdo;
    
    public function __construct() {
        // 加载数据库配置
        require_once ROOT_PATH . '/config/database.php';
        
        try {
            $this->pdo = new PDO(
                "mysql:host={$config['host']};dbname={$config['database']};charset=utf8",
                $config['username'],
                $config['password']
            );
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }
    }
    
    public function query($sql, $params = []) {
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            
            // 如果是SELECT查询，返回结果集
            if (strpos(strtoupper($sql), 'SELECT') === 0) {
                return $stmt->fetchAll(PDO::FETCH_ASSOC);
            }
            
            // 对于INSERT，返回最后插入的ID
            if (strpos(strtoupper($sql), 'INSERT') === 0) {
                return $this->pdo->lastInsertId();
            }
            
            // 对于UPDATE或DELETE，返回受影响的行数
            return $stmt->rowCount();
        } catch (PDOException $e) {
            die("查询执行失败: " . $e->getMessage());
        }
    }
}
?>